//
//  MagazineDetailViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/4.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "MagazineDetailViewController.h"
#import "MagazineHeaderTableViewCell.h"
#import "MagazineFooterTableViewCell.h"
#import "BookReadingViewController.h"
#import "LoginViewController.h"
#import "RegistViewController.h"

@interface MagazineDetailViewController () <LoginDelegate>

/** 下载完成弹窗 */
@property (nonatomic, strong) UIView * overAlert;
/** 杂志封面 */
@property (nonatomic, strong) UIView * coverView;
/** 杂志标题 */
@property (nonatomic, strong) UILabel * titleLabel;
/** 期数 */
@property (nonatomic, strong) UILabel * timeLabel;
/** 黑色下划线 */
@property (nonatomic, strong) UIView * blackLine;
/** 在线阅读按钮 */
@property (nonatomic, strong) UIButton * readButton;
/** 下载按钮 */
@property (nonatomic, strong) UIButton * downloadButton;
/** 进度条 */
@property (nonatomic, strong) UIProgressView * progressView;
/** 期刊简介按钮 */
@property (nonatomic, strong) UIButton * summaryButton;
/** 期刊简介视图 */
@property (nonatomic, strong) UIView * summaryView;
/** 往期按钮 */
@property (nonatomic, strong) UIButton * pastButton;
/** 往期视图 */
@property (nonatomic, strong) UIScrollView * pastView;
/** 出版信息按钮 */
@property (nonatomic, strong) UIButton * infoButton;
/** 出版信息视图 */
@property (nonatomic, strong) UIView * infoView;
/** 书籍本地路径 */
@property (nonatomic, copy) NSString * filePath;
/** 杂志详情数据源 */
@property (nonatomic, strong) NSDictionary * magazineDetailDic;
/** 某一期的期刊数据源 */
@property (nonatomic, strong) NSDictionary * magazinePeriodDic;
/** BookReadingVC */
@property (nonatomic, strong) BookReadingViewController * bookReadingVC;
/** 封面 */
@property (nonatomic, strong) UIImageView * coverImageView;


@end

@implementation MagazineDetailViewController

#pragma mark - lazy load

- (UIView *)infoView{
    if (!_infoView) {
        _infoView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.summaryButton.frame), SCREEN_W, HeightScale(260))];
        _infoView.hidden = YES;
        
        //发行周期
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(WidthScale(20), HeightScale(20), SCREEN_W - WidthScale(40), HeightScale(40))];
        label1.text = [NSString stringWithFormat:@"发行周期 : %@", self.magazineDetailDic[@"period"]];
        label1.textColor = COLOR_BLACK;
        label1.font = FONTSIZE(17);
        
        //国内刊号
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(WidthScale(20), CGRectGetMaxY(label1.frame), SCREEN_W - WidthScale(40), HeightScale(40))];
        label2.text = [NSString stringWithFormat:@"国内刊号 : %@", self.magazineDetailDic[@"code"]];
        label2.textColor = COLOR_BLACK;
        label2.font = FONTSIZE(17);
        
        //出版社
        UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(WidthScale(20), CGRectGetMaxY(label2.frame), SCREEN_W - WidthScale(40), HeightScale(40))];
        label3.text = [NSString stringWithFormat:@"出版社 : %@", self.magazineDetailDic[@"province"]];
        label3.textColor = COLOR_BLACK;
        label3.font = FONTSIZE(17);
        
        [_infoView addSubview:label1];
        [_infoView addSubview:label2];
        [_infoView addSubview:label3];
        
    }
    return _infoView;
}

- (UIScrollView *)pastView{
    if (!_pastView) {
        _pastView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.summaryButton.frame), SCREEN_W, HeightScale(260))];
        _pastView.showsVerticalScrollIndicator = NO;
        
        
        NSArray *tempArr = [NSArray arrayWithArray:self.magazineDetailDic[@"periodNum"]];
        
        _pastView.contentSize = CGSizeMake(SCREEN_W, ((tempArr.count % 3) ? (tempArr.count / 3 + 1) : (tempArr.count / 3)) * HeightScale((36 + 12)) + HeightScale(12));
        
        CGFloat buttonW = (SCREEN_W - WidthScale((12 + 20 + 20 + 12))) / 3;
        NSMutableArray *buttonArr = [NSMutableArray array];
        for (int i = 0; i < tempArr.count; i ++) {
            UIButton *periodButton = [[UIButton alloc] initWithFrame:CGRectMake(i % 3 * (buttonW + WidthScale(20)) + WidthScale(12), i / 3 * HeightScale((36 + 12)) + HeightScale(12), buttonW, HeightScale(36))];
            periodButton.layer.cornerRadius = WidthScale(8);
            [periodButton setTitle:tempArr[i][@"issuename"] forState:UIControlStateNormal];
            [periodButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
            periodButton.layer.borderWidth = WidthScale(1);
            periodButton.layer.borderColor = COLOR_BLACK.CGColor;
            periodButton.titleLabel.font = FONTSIZE(15);
            periodButton.tag = 10 + i;
            [buttonArr addObject:periodButton];
            
            if (i == 0) {
                periodButton.selected = YES;
                [periodButton setBackgroundColor:COLOR_GREEN];
                self.magazinePeriodDic = self.magazineDetailDic[@"periodNum"][0];
            }
            
            __weak typeof(self)weakSelf = self;
            [periodButton initWithBlock:^(UIButton * button) {
                
                DLog(@"%@", button.titleLabel.text);
                
                
                for (UIButton *tempButton in buttonArr) {
                    tempButton.selected = NO;
                    [tempButton setBackgroundColor:COLOR_CLEAR];
                }
                button.selected = YES;
                [button setBackgroundColor:COLOR_GREEN];
                weakSelf.magazinePeriodDic = weakSelf.magazineDetailDic[@"periodNum"][button.tag - 10];
                weakSelf.timeLabel.text = weakSelf.magazinePeriodDic[@"issuename"];
                [weakSelf.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, weakSelf.magazinePeriodDic[@"coverimgpath"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
                
                //添加当前这一期到浏览历史
                [weakSelf requestHistory];
                
                //判断本期是否已下载
                if ([weakSelf alreadyExist] == 0) {
                    //未下载
                    [weakSelf.readButton setImage:ImageNamed(@"在线阅读") forState:UIControlStateNormal];
                    weakSelf.downloadButton.hidden = NO;
                } else {
                    //已下载
                    [weakSelf.readButton setImage:ImageNamed(@"开始阅读") forState:UIControlStateNormal];
                    weakSelf.downloadButton.hidden = YES;
                }
                
            } for:UIControlEventTouchUpInside];
            
            [_pastView addSubview:periodButton];
        }
    }
    return _pastView;
}

- (UIView *)summaryView{
    if (!_summaryView) {
        _summaryView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.summaryButton.frame), SCREEN_W, HeightScale(260))];
        _summaryView.hidden = YES;
        
        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(WidthScale(15), HeightScale(10), SCREEN_W - WidthScale(30), _summaryView.frame.size.height - HeightScale(20))];
        textView.showsVerticalScrollIndicator = NO;
        textView.backgroundColor = COLOR_CLEAR;
        textView.editable = NO;
        textView.font = FONTSIZE(16);
        textView.textColor = COLOR_FONTBLACK;
        textView.text = [NSString stringWithFormat:@"        %@", self.magazineDetailDic[@"summarytext"]];
        [_summaryView addSubview:textView];
    }
    return _summaryView;
}

- (UIButton *)infoButton{
    if (!_infoButton) {
        _infoButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W / 3 * 2, self.summaryButton.frame.origin.y, SCREEN_W / 3, HeightScale(40))];
        [_infoButton setTitle:@"出版信息" forState:UIControlStateNormal];
        [_infoButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_infoButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _infoButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_infoButton initWithBlock:^(UIButton *button) {
            DLog(@"出版信息");
            if (!button.selected) {
                button.selected = YES;
                weakSelf.infoView.hidden = NO;
                weakSelf.summaryButton.selected = weakSelf.pastButton.selected = NO;
                weakSelf.summaryView.hidden = weakSelf.pastView.hidden = YES;
            }
        } for:UIControlEventTouchUpInside];
    }
    return _infoButton;
}

- (UIButton *)pastButton{
    if (!_pastButton) {
        _pastButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W / 3, self.summaryButton.frame.origin.y, SCREEN_W / 3, HeightScale(40))];
        [_pastButton setTitle:@"往  期" forState:UIControlStateNormal];
        [_pastButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_pastButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _pastButton.titleLabel.font = FONTSIZE(17);
        _pastButton.selected = YES;
        __weak typeof(self)weakSelf = self;
        [_pastButton initWithBlock:^(UIButton *button) {
            DLog(@"往期")
            if (!button.selected) {
                button.selected = YES;
                weakSelf.pastView.hidden = NO;
                weakSelf.summaryButton.selected = weakSelf.infoButton.selected = NO;
                weakSelf.summaryView.hidden = weakSelf.infoView.hidden = YES;
            }
            
        } for:UIControlEventTouchUpInside];
        
        UIView *vLine = [[UIView alloc] initWithFrame:CGRectMake(_pastButton.frame.size.width - WidthScale(0.6), HeightScale(10), WidthScale(0.6), HeightScale(24))];
        vLine.backgroundColor = COLOR_GREEN;
        
        [_pastButton addSubview:vLine];
    }
    return _pastButton;
}

- (UIButton *)summaryButton{
    if (!_summaryButton) {
        _summaryButton = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.progressView.frame) + HeightScale(5), SCREEN_W / 3, HeightScale(40))];
        [_summaryButton setTitle:@"期刊简介" forState:UIControlStateNormal];
        [_summaryButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_summaryButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _summaryButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_summaryButton initWithBlock:^(UIButton *button) {
            DLog(@"期刊简介");
            if (!button.selected) {
                button.selected = YES;
                weakSelf.summaryView.hidden = NO;
                weakSelf.pastButton.selected = weakSelf.infoButton.selected = NO;
                weakSelf.pastView.hidden = weakSelf.infoView.hidden = YES;
            }
            
        } for:UIControlEventTouchUpInside];
        
        UIView *vLine = [[UIView alloc] initWithFrame:CGRectMake(_summaryButton.frame.size.width - WidthScale(0.6), HeightScale(10), WidthScale(0.6), HeightScale(20))];
        vLine.backgroundColor = COLOR_GREEN;
        
        
        UIView *hLine1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, HeightScale(0.6))];
        UIView *hLine2 = [[UIView alloc] initWithFrame:CGRectMake(0, _summaryButton.frame.size.height - HeightScale(0.6), SCREEN_W, HeightScale(0.6))];
        [_summaryButton addSubview:hLine1];
        [_summaryButton addSubview:hLine2];
        
        hLine1.backgroundColor = COLOR_GREEN;
        hLine2.backgroundColor = COLOR_GREEN;
        
        [_summaryButton addSubview:vLine];

    }
    return _summaryButton;
}

- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(WidthScale(10), CGRectGetMaxY(self.readButton.frame) + HeightScale(3), SCREEN_W - WidthScale(10), HeightScale(5))];
        _progressView.layer.cornerRadius = 2;
        _progressView.progressTintColor = COLOR_GREEN;
        _progressView.transform = CGAffineTransformMakeScale(1.0f,3.0f);
        _progressView.hidden = YES;
    }
    return _progressView;
}

- (UIButton *)downloadButton{
    if (!_downloadButton) {
        _downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(85), self.readButton.frame.origin.y, WidthScale(75), HeightScale(30))];
        [_downloadButton setImage:ImageNamed(@"下载") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [_downloadButton initWithBlock:^(id obj) {
            DLog(@"下载")
            [weakSelf downloadMagazine:obj];
        } for:UIControlEventTouchUpInside];
    }
    return _downloadButton;
}

#pragma mark - read
- (UIButton *)readButton{
    if (!_readButton) {
        _readButton = [[UIButton alloc] initWithFrame:CGRectMake(WidthScale(10), CGRectGetMaxY(self.blackLine.frame) + HeightScale(5), WidthScale(75), HeightScale(30))];
        if ([self alreadyExist]) {
            [_readButton setImage:ImageNamed(@"开始阅读") forState:UIControlStateNormal];
            self.downloadButton.hidden = YES;
        } else {
            [_readButton setImage:ImageNamed(@"在线阅读") forState:UIControlStateNormal];
        }

        __weak typeof(self)weakSelf = self;
        [_readButton initWithBlock:^(id obj) {
            
            //判断是否登录
            if (![AppDelegate shareDelegate].userModel) {
                //未登录
                [weakSelf loginPresent];
            } else {
                DLog(@"阅读");
                [SVProgressHUD show];
                if (weakSelf.downloadButton.hidden) {
                    DLog(@"已下载，本地阅读");
                    weakSelf.bookReadingVC = [[BookReadingViewController alloc] init];
                    weakSelf.bookReadingVC.filePath = weakSelf.filePath;
                    weakSelf.bookReadingVC.isMagazine = YES;
                    weakSelf.bookReadingVC.pages = [weakSelf.magazinePeriodDic[@"pages"] integerValue];
                    weakSelf.bookReadingVC.dataDic = weakSelf.magazinePeriodDic;
                    weakSelf.bookReadingVC.native = YES;
                } else {
                    DLog(@"在线阅读");
                    weakSelf.bookReadingVC = [[BookReadingViewController alloc] init];
                    weakSelf.bookReadingVC.pages = [weakSelf.magazinePeriodDic[@"pages"] integerValue];
                    weakSelf.bookReadingVC.isMagazine = YES;
                    weakSelf.bookReadingVC.dataDic = weakSelf.magazinePeriodDic;
                    weakSelf.bookReadingVC.filePath = weakSelf.magazinePeriodDic[@"filepath"];
                }
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:weakSelf.bookReadingVC];
                nav.navigationBar.hidden = YES;
                [weakSelf presentViewController:nav animated:YES completion:^{
                    [SVProgressHUD dismiss];
                }];
            }
            
        } for:UIControlEventTouchUpInside];
    }
    return _readButton;
}

- (UIView *)blackLine{
    if (!_blackLine) {
        _blackLine = [[UIView alloc] initWithFrame:CGRectMake(WidthScale(10), CGRectGetMaxY(self.titleLabel.frame), SCREEN_W - WidthScale(20), HeightScale(1))];
        _blackLine.backgroundColor = COLOR_FONTBLACK;
    }
    return _blackLine;
}

- (UILabel *)timeLabel{
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(120), CGRectGetMaxY(self.coverView.frame), WidthScale(110), HeightScale(40))];
        NSArray *tempArr = [NSArray arrayWithArray:self.magazineDetailDic[@"periodNum"]];
        _timeLabel.text = [NSString stringWithFormat:@"%@", tempArr[0][@"issuename"]];
        _timeLabel.font = FONTSIZE(17);
        _timeLabel.textAlignment = NSTextAlignmentRight;
    }
    return _timeLabel;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.coverView.frame), SCREEN_W - 120, HeightScale(40))];
        _titleLabel.text = [NSString stringWithFormat:@"【%@】", self.magazineDetailDic[@"name"]];
        _titleLabel.font = FONTSIZE(17);
        _titleLabel.adjustsFontSizeToFitWidth = YES;
        
    }
    return _titleLabel;
}

- (UIView *)coverView{
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, HeightScale(345))];
        UIImageView *coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(168)) / 2, HeightScale(80), WidthScale(168), HeightScale(230))];
        self.coverImageView = coverImageView;
        [coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.magazineDetailDic[@"coverimgpath"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
        
        _coverView.backgroundColor = COLOR_BOOKDETAILBGCOLOR;
        [_coverView addSubview:coverImageView];
    }
    return _coverView;
}

- (UIView *)overAlert{
    if (!_overAlert) {
        _overAlert = [[UIView alloc] initWithFrame:self.view.bounds];
        _overAlert.backgroundColor = COLOR_alphaBGCOLOR;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(97), HeightScale(250), WidthScale(220), HeightScale(157))];
        imageView.image = ImageNamed(@"xiazaiwancheng");
        
        [_overAlert addSubview:imageView];
    }
    return _overAlert;
    
}

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"详情";
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self requestMagazineDetail];
//
//    //添加统计
//    [self requestStatistics];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H + [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [Tool setNavigationBarType:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)dealloc{
    DLog(@"%s", __func__);
}

#pragma mark - 查看本地是否有这本期刊

- (BOOL)alreadyExist{
    //本地期刊
    NSArray *nativeMagazineArr =  [[NSFileManager defaultManager] contentsOfDirectoryAtPath:MagazinesPath error:nil];
    
    for (NSString *magazineName in nativeMagazineArr) {
        if ([magazineName isEqualToString:[NSString stringWithFormat:@"%@%@", self.magazineDetailDic[@"name"], self.magazinePeriodDic[@"issuename"]]]) {
            self.filePath = [MagazinesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", self.magazineDetailDic[@"name"], self.magazinePeriodDic[@"issuename"]]];
            return YES;
        }
    }
    return NO;
}

- (void)loginPresent{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.delegate = self;
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)registPresent{
    RegistViewController *registVC = [[RegistViewController alloc] init];
    [self presentViewController:registVC animated:YES completion:nil];
}

- (void)loginSuccess{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
    
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    
    [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:userDic];
    
    DLog(@"%@", [AppDelegate shareDelegate].userModel.userId);
}

#pragma mark - data request

- (void)requestMagazineDetail{
    NSString *URL = [NSString stringWithFormat:KMagazineDetail, KHostAddress, self.magazineDic[@"id"]];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.magazineDetailDic = responseObject[@"data"];
            
            self.magazinePeriodDic = self.magazineDetailDic[@"periodNum"][0];
            
            [self alreadyExist];
            
            [self.view addSubview:self.coverView];

            [self.view addSubview:self.titleLabel];

            [self.view addSubview:self.timeLabel];

            [self.view addSubview:self.blackLine];

            [self.view addSubview:self.readButton];

            [self.view addSubview:self.downloadButton];

            [self.view addSubview:self.progressView];

            [self.view addSubview:self.summaryButton];

            [self.view addSubview:self.pastButton];

            [self.view addSubview:self.infoButton];

            [self.view addSubview:self.summaryView];

            [self.view addSubview:self.infoView];

            [self.view addSubview:self.pastView];

            [self requestHistory];
            
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 下载期刊 */
- (void)downloadMagazine:(UIButton *)button{
    if (![AppDelegate shareDelegate].userModel) {
        //没登录
        [self loginPresent];
    } else {
        //透明色视图遮挡屏幕，屏蔽下载过程中，用户进行其他操作。
        UIView *backView = [[UIView alloc] initWithFrame:self.view.bounds];
        backView.backgroundColor = COLOR_CLEAR;
        [[AppDelegate shareDelegate].window addSubview:backView];
        
        //显示下载进度条
        self.progressView.hidden = NO;
        
        //开始下载请求
        NSString *magazineZipURL = [NSString stringWithFormat:@"%@%@.zip", KHostAddress, self.magazinePeriodDic[@"filepath"]];
        [ZRRequestManager downLoadWithURL:magazineZipURL progress:^(NSProgress *progress) {
            
            //获取下载进度百分比
            float value = 1.0 * progress.completedUnitCount / progress.totalUnitCount;
            //子线程中刷新下载进度条进度
            dispatch_async(dispatch_get_main_queue(), ^{
                self.progressView.progress = value;
            });
            
            DLog(@"下载进度 -- %.1lf%%", 100.0 * value);
            
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            //下载文件目标路径
            NSString *magazinePath = [MagazinesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.zip", self.magazineDetailDic[@"name"], self.magazinePeriodDic[@"issuename"]]];
            self.filePath = [magazinePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            return [NSURL fileURLWithPath:self.filePath];
            
        } downLoadSuccess:^(NSURLResponse *response, NSURL *filePath) {
            
            //移除透明色视图遮挡
            [backView removeFromSuperview];
            
            //隐藏下载进度条
            self.progressView.hidden = YES;
            
            //显示下载完成弹窗(1s后自动消失)
            [[AppDelegate shareDelegate].window addSubview:self.overAlert];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.overAlert removeFromSuperview];
            });
            
            //“在线阅读”换成“开始阅读”
            [self.readButton setImage:ImageNamed(@"开始阅读") forState:UIControlStateNormal];
            //下载完成，隐藏下载按钮
            self.downloadButton.hidden = YES;
            
            
            DLog(@"%@", filePath);
            
            //解压zip
            [SSZipArchive unzipFileAtPath:self.filePath toDestination:[self.filePath stringByDeletingPathExtension] progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
                nil;
            } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nonnull error) {
                //解压完成后，删除沙盒中的zip文件，只保留已解压的书刊目录。
                [[NSFileManager defaultManager] removeItemAtPath:self.filePath error:nil];
                self.filePath = [self.filePath stringByDeletingPathExtension];
            }];
            
            //添加到书架
            
            [self requestAddShelf];
            
        } failure:^(NSError *error) {
            [ZRProgressHUD showMsgWithoutView:@"下载失败，请稍后重试"];
            [backView removeFromSuperview];
            self.progressView.hidden = YES;
            DLog(@"%@", error);
        }];
    }
}

/** 添加浏览历史 */
- (void)requestHistory{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        
        NSString *URL = [NSString stringWithFormat:KaddHistory, KHostAddress, self.magazineDetailDic[@"id"], @(4), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"添加浏览历史");
        } failure:^(NSError *error) {
            DLog(@"添加浏览历史失败");
        }];
    }
    
}

/** 添加到书架 */
- (void)requestAddShelf{
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddShelf, KHostAddress, self.magazinePeriodDic[@"issueid"], @(4), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加书架成功");
            } else {
                DLog(@"添加书架失败");
            }
            
            
        } failure:^(NSError *error) {
            DLog(@"添加书架失败");
        }];
    }
}

/** 添加统计 */
- (void)requestStatistics{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(4), self.magazineDic[@"id"]];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

@end
